package no.ntnu.fp.net.Apps;

import java.util.HashMap;
import java.util.Map;


public class MultipleClientHost implements Runnable {
	private static Map<Integer, MyHost> usedPorts = new HashMap<Integer,MyHost>();
	private static Map<MyHost, Thread> threadList = new HashMap<MyHost, Thread>();
	private static Map<MyHost, Boolean> runningHosts = new HashMap<MyHost, Boolean>();
	
	private boolean isRunning = true;
	
	public MultipleClientHost() {
	}
	
	/**
	 * Creates a new Host instance and adds
	 * it to the host list with the corresponding
	 * port value
	 * 
	 * @param port
	 */
	public synchronized void addHost(int port){
		if (usedPorts.get(port) != null) {
			System.out.println("Host already added on this port");
		}
		else {
			MyHost host = new MyHost(port);
			usedPorts.put(port, host);
			Thread run = new Thread(host);
			threadList.put(host, run);
			runningHosts.put(host, false);
			System.out.println("System added host to port "+port);
		}
	}
	
	/**
	 * Start the Multiple Client Host application
	 * implementet in the MultipleClientHost Class 
	 */
	public void run() {
		while(isRunning) {
			if (usedPorts.values().size() != 0 && runningHosts.values().size() != 0 && threadList.values().size() != 0) {
				for (MyHost host : usedPorts.values()) {
					if (!runningHosts.get(host) && threadList.get(host) != null){
						synchronized (host) {
							try {
								threadList.get(host).start();
								runningHosts.put(host, true);
								Thread.sleep(1000);
								
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					
					}
				}
			}
		}
	}
	
	/**
	 * 	Returns the host using port
	 * @param port
	 * 		- port integer
	 * @return A host using port
	 */
	public MyHost getHostOnPort(int port) {
		return usedPorts.get(port);
	}
	
	public static void main(String[] args) {
		MultipleClientHost host = new MultipleClientHost();
		host.addHost(1337);
		(new Thread(host)).start();
		host.addHost(1338);
		
	}
}
